let userId = window.localStorage.getItem("DICS_userId");
import { formatSeconds } from "@/utils/index";
export default {
    data() {
        return {
            websock: null, //建立的连接
            lockReconnect: false, //是否真正建立连接
            timeout: 1 * 1000, //30秒一次心跳
            timeoutObj: null, //外层心跳倒计时
            serverTimeoutObj: null, //内层心跳检测
            timeoutnum: null, //断开 重连倒计时
        }
    },
    destroyed() {
        //页面销毁时关闭长连接
        // this.websocketclose();
    },
    methods: {
        initWebSocket() {
            //初始化weosocket
            let socket_api = process.env.VUE_APP_SOCKET_API;
            const url = `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}${socket_api}`;
            this.websock = new WebSocket(`${url}/equipment/websocket/${userId}`);
            this.websock.onopen = this.websocketonopen;
            this.websock.onmessage = this.websocketonmessage;
            this.websock.onerror = this.websocketonerror;
            // this.websock.onclose = this.websocketclose;
        },
        reconnect() {
            //重新连接
            var that = this;
            if (that.lockReconnect) {
                // 是否真正建立连接
                return;
            }
            that.lockReconnect = true;
            //没连接上会一直重连，设置延迟避免请求过多
            that.timeoutnum && clearTimeout(that.timeoutnum);
            // 如果到了这里断开重连的倒计时还有值的话就清除掉
            that.timeoutnum = setTimeout(function () {
                //然后新连接
                that.initWebSocket();
                that.lockReconnect = false;
            }, 1000);
        },
        reset() {
            //重置心跳
            var that = this;
            //清除时间（清除内外两个心跳计时）
            clearTimeout(that.timeoutObj);
            clearTimeout(that.serverTimeoutObj);
            //重启心跳
            that.start();
        },
        start() {
            console.info("开启心跳");
            //开启心跳
            var self = this;
            self.timeoutObj && clearTimeout(self.timeoutObj);
            // 如果外层心跳倒计时存在的话，清除掉
            self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
            // 如果内层心跳检测倒计时存在的话，清除掉
            self.timeoutObj = setTimeout(function () {
                // 重新赋值重新发送 进行心跳检测
                //这里发送一个心跳，后端收到后，返回一个心跳消息，
                if (self.websock.readyState == 1) {
                    console.info("连接正常");
                    //如果连接正常
                    self.websock.send("ping");
                } else {
                    console.info("否则重连");
                    //否则重连
                    self.reconnect();
                }
                self.serverTimeoutObj = setTimeout(function () {
                    // 在三秒一次的心跳检测中如果某个值3秒没响应就关掉这次连接
                    //超时关闭
                    self.websock.close();
                }, self.timeout);
            }, self.timeout);
            // 3s一次
        },

        websocketonopen(e) {
            //连接建立之后执行send方法发送数据
            console.log("成功");
            this.websocketOpenSuccess()
        },
        websocketOpenSuccess(){},
        websocketonerror() {
            //连接建立失败重连
            console.log("失败");
            this.initWebSocket();
        },

        websocketsend(Data) {
            //数据发送

            this.websock.send(Data);
        },
        websocketclose(e) {
            //关闭
            this.websock.close()
            console.log("断开连接");
        },
        setItemData(list, res, type) {
            list.forEach((item) => {
                // 如果是任务表格，判断任务ID，如果是设备，判断设备ID
                if ((type == 'working' && item.workingId == res.workingId) || (type == 'equipment' && item.address == res.id)) {
                    // room=>任务名称 ：2，设备状态：0，进度：1
                    if (res.room == 1) {
                        item.productionStatus = this.toPercent(res.productionStatus);
                        item.detail = res.detail; //当前任务总层数
                        item.currentLayerFinished = res.currentLayerFinished; //当前任务打印层数
                    } else if (res.room == 2) {
                        //任务名称
                        item.thickness=res.thickness
                        item.taskName = res.taskName;
                    } else if (res.room == 0) {
                        //设备状态,排队任务
                        item.equipmentType = res.equipmentType;

                        this.equipmentStatusChange(res) // 仅看板需要处理这里的值，用来重新请求设备综合数据
                        item.taskQuantity = res.taskQuantity ? res.taskQuantity : "";
                    } else if (res.room == 4) {
                        item.remaining = res.remaining;
                    } else if (res.room == 5) {
                        //报警
                        item.alramDataNum = res.alramDataNum;
                    } else if (res.room == 3) {
                        //气氛参数
                        ["oxygen", "cabinPressure", "filterPressureDiff", "fanFlux", "buildCylinderTemperature", "fanPipeTemp"].forEach((key) => {
                            if (key in res) {
                                item[key] = res[key];
                            }
                        });
                    } else if (res.room == 6) {
                        item.taskStatus = res.taskStatus//任务状态
                        this.workingStatusChange(res)// 仅看板需要处理这里的值，用来重新请求任务综合数据
                     }else if(res.room== 7){
                        item.imageUrl = 'data:image/png;base64,'+res.image//打印图片
                    }
                }
            });
        },
        // 下面2个方法实际无用，但mixins里面用到了（看板需要这2个方法回调）
        workingStatusChange() { },
        equipmentStatusChange() { },
        formatSeconds: formatSeconds,
        // 看板数据表格倒计时方法
        setRemainingTime(list) {
            let _this = this
            list.forEach((item) => {
                item.remainingSave = item.remaining;
                item.second = this.formatSeconds(item.remainingSave);
                clearInterval(item.timer);
                item.timer = setInterval(() => {
                    item.remainingSave = parseFloat(item.remainingSave) - 1;
                    if (item.remainingSave == -1) {
                        clearInterval(item.timer);
                        return;
                    }
                    item.second = _this.formatSeconds(item.remainingSave);
                }, 1000);
            });
        },
    }
}
